<template>
  <!-- 查询部分 -->
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form
            :model="queryData"
            layout="inline"
            size="small"
            v-if="permissionStore.hasPermisson('jtlxlb.cx')"
          >
            <a-form-item label="类型编号">
              <!-- <a-select popup-container="html"  class="bacClass" allow-search allowClear :style="{ width: '200px' }"
                                    :loading="loading" @search="handleSearch" :filter-option="false"
                                    v-model.trim="queryData.typeCode" @click="handleSearchs">
                                    <a-option v-for="item in options" :value="item.typeCode">{{
                                        item.typeCode
                                    }}</a-option>
                                </a-select> -->
              <a-input
                class="bacClass"
                v-model.trim="queryData.typeCode"
                @press-enter="huiche"
                allow-clear
                style="width: 200px"
              ></a-input>
            </a-form-item>
            <a-form-item label="类型名称">
              <!-- <a-select popup-container="html"  class="bacClass" allow-search allowClear :style="{ width: '200px' }"
                                    :loading="loading1" @search="handleSearch1" :filter-option="false"
                                    v-model.trim="queryData.typeName" @click="handleSearchs1s">
                                    <a-option v-for="item in options1" :value="item.typeName">{{
                                        item.typeName
                                    }}</a-option>
                                </a-select> -->
              <a-input
                class="bacClass"
                v-model.trim="queryData.typeName"
                @press-enter="huiche"
                allow-clear
                style="width: 200px"
              ></a-input>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar
            :items="pageData.btnList"
            @select="selectHandler"
            @add="addHandler"
            @del="deleteHandler"
            @export="exports"
            style="float: right"
          ></Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar"> </div>
    </template>

    <template #pageTabel>
      <!-- <a-tabs   :justify="true">
                <a-tab-pane title="机台类型"> -->
      <!-- <a-table size="mini" style="height:100%" :scrollbar="true" sticky-header
                                 @change="handleChange"  :draggable="{type:'handle',width:20,fixed:true}"
                                 @page-change="pagination.change" stripe
                                 :bordered="true" :columns="columns"
                                 :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
                                 v-model:selected-keys="selectedRowKeys" :loading="pageData.pageLoading"
                                 :data="table.dataList"
                                 :pagination="false"
                                 :rowKey="rowKey" :scroll="{x:'100%',y:'100%' ,maxHeight:'100%'}">
                        <template #action="{ record }">
                            <a-button type="primary" size="mini" status="warning" @click="edit(record)">
                                <template #icon>
                                    <icon-edit/>
                                </template>
                                修 改
                            </a-button>
                        </template>
                    </a-table> -->
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        rowSelection="multiple"
        @grid-ready="gridReady"
        style="height: calc(100% - 45px)"
        class="ag-theme-alpine"
        :defaultColDef="defaultColDef"
        :rowData="table.dataList"
        :columnDefs="tc"
        :localeText="localeText1"
        @columnResized="onColumnResized"
        @columnMoved="onColumnMoved"
      >
      </AgGridVuesCopys>
      <paginationCopys
        :total="total"
        show-total
        show-jumper
        show-page-size
        @change="PageSize"
        @page-size-change="change1"
        style="justify-content: center"
        :page-size="pagination.pageSize"
        :current="pagination.page"
      />
      <!-- </a-tab-pane>
            </a-tabs> -->
    </template>

    <a-drawer
      :style="{ zIndex: 999 }"
      :mask-closable="false"
      :width="400"
      :visible="pageData.showAdd"
      :ok-loading="pageData.pageLoading"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
      cancel-text="关闭"
      ok-text="保存"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" :model="formData" layout="horizontal">
          <!-- <a-form-item
            label="类型编号"
            field="typeCode"
            label-col-flex="100px"
            :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input
              class="bacClass"
              placeholder=""
              @blur="inputBlur"
              v-model.trim="formData.typeCode"
            />
          </a-form-item> -->
          <a-form-item
            label-col-flex="100px"
            field="typeName"
            label="类型名称"
            :rules="[{ required: true, message: '类型名称必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" v-model="formData.typeName" placeholder="" />
          </a-form-item>
          <!-- <a-form-item
            field="maxCapacity"
            label="极限日产能"
            :rules="[{ required: true, message: '极限日产能必填' }]"
            label-col-flex="100px"
            :validate-trigger="['change', 'blur']"
          >
            <a-input-number
              class="bacClass"
              :min="0"
              :max="9999999999"
              v-model="formData.maxCapacity"
              placeholder=""
            />
          </a-form-item> -->
          <!-- <a-form-item label="单位" label-col-flex="100px">
            <a-select popup-container="html" 
              class="bacClass"
              v-model="formData.unit"
              @search="searchUnit"
              @focus="focusunit"
              allow-clear
              allow-search
              :filter-option="false"
            >
              <a-option v-for="item in pageData.unitList" :value="item['detailName']"
                >{{ item['detailName'] }}
              </a-option>
            </a-select>
          </a-form-item> -->
          <a-form-item label="备注" label-col-flex="100px">
            <a-textarea
              class="bacClass"
              placeholder=""
              v-model="formData.remark"
              :max-length="400"
              allow-clear
              show-word-limit
            />
            <!-- <a-input v-model="formData.remark" /> -->
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import {
    useTableColumn,
    useTable,
    usePagination,
    useRowSelection,
    useRowKey,
  } from '@/hooks/table'
  import { post } from '@/api/http'
  import { Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  
  import { localeText } from '@/api/aggridZw'
  import { pagingList } from '@/api/paging'
  import usePermission from '@/store/modules/permission'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'

  const headerShow = ref<boolean>(true)
  const localeText1: any = ref(localeText)
  const pagingList1: any = ref(pagingList)

  //定义TS类型
  interface Firm {
    name: string
    id: number
  }

  interface Cloth {
    code: string
  }

  interface MachineType {
    id: any
    // typeCode: any
    typeName: any
    maxCapacity: number | undefined
    remark: any
    unit: any
    // //删除
    // "deleteState": number | string | undefined,
    // // 作废的状态
    // "obsoleteState": number | string | undefined
  }

  const isChiese = (value: string, cb: Function) => {
    return new Promise<void>((resolve) => {
      if (window.encodeURI(value).indexOf('%') !== -1) {
        cb('填写的值不能包含中文！')
      }
      resolve()
    })
  }

  // const inputBlur = () => {
  //   formData.typeCode = formData.typeCode?.toUpperCase()
  // }

  const focusunit = () => {
    getUnitList('')
  }
  // 单位下拉框
  const searchUnit = (value: any) => {
    if (value) {
      loading.value = true
      getUnitList(value)
      options.value = pageData.unitList
      loading.value = false
    } else {
      options.value = []
    }
  }

  // 单位下拉框
  const getUnitList = (val: any) => {
    post({
      url: 'dict/dictTypeDetail/getListByMap',
      data: {
        codeType: 17,
        detailName: val,
      },
    }).then(({ code, data }: any) => {
      if (code == 200) {
        pageData.unitList = data
      } else {
        Message.error({
          content: '查询失败',
          duration: 5000,
        })
      }
    })
  }
  //查询表单
  const queryData = reactive({
    typeName: '',
    typeCode: '',
  })
  //下拉框和弹窗的数据变量
  const pageData = reactive<{
    gcList: Firm[]
    clothList: Cloth[]
    unitList: []
    showAdd: boolean
    sideTitle: string
    rHeight: any
    pageLoading: boolean
    btnList: any[]
  }>({
    //类型编号数据
    gcList: [],
    //类型名称数据
    clothList: [],
    //弹窗是否显示
    showAdd: false,
    unitList: [],
    //弹窗的标题
    sideTitle: '新增类型',
    rHeight: 0,
    pageLoading: false,
    btnList: [],
  })

  //修改
  //record：是点击修改时，得到当前被点击项的对象数据
  const edit = (record: MachineType) => {
    //数据回填
    formData.id = Number(record.id)

    formData.typeName = record.typeName
    formData.maxCapacity = record.maxCapacity
    // formData.typeCode = record.typeCode
    formData.remark = record.remark
    formData.unit = record.unit
    formData.remark = record.remark
    //显示弹窗
    pageData.showAdd = true
    //弹窗的标题
    pageData.sideTitle = '修改类型'
  }

  //表格的列描述信息|
  const columns = useTableColumn([
    // {
    //   title: '序号',
    //   // 列信息的标识，对应表格的数据
    //   dataIndex: 'typeCode',
    //   key: 'typeCode',
    //   width: 150,
    // },
    {
      title: '设备机型',
      dataIndex: 'typeName',
      width: 150,
      key: 'typeName',
    },
    // {
    //   title: '极限日产能',
    //   dataIndex: 'maxCapacity',
    //   width: 150,
    //   key: 'maxCapacity',
    // },
    // {
    //   title: '单位',
    //   dataIndex: 'unit',
    //   width: 150,
    //   key: 'unit',
    // },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 150,
      key: 'remark',
    },
    {
      title: '创建人',
      key: 'createName',
      dataIndex: 'createName',
      width: 150,
    },
    {
      title: '创建时间',
      key: 'createTime',
      dataIndex: 'createTime',
      width: 200,
    },
    {
      title: '修改人',
      key: 'updateName',
      dataIndex: 'updateName',
      width: 150,
    },
    {
      title: '修改时间',
      key: 'updateTime',
      dataIndex: 'updateTime',
      width: 200,
    },
    // {
    //     title: "备注",
    //     key: "remark",
    //     dataIndex: "remark",
    //     width: 150,
    // },
    {
      title: '操作',
      key: 'id',
      slotName: 'action',
      width: 150,
      fixed: 'right',
    },
  ])

  let tc: any[] = columns.map((o) => {
    let obj = {
      headerName: o.title,
      field: o.key,
      pinned: o['fixed'],
      tooltipField: o.key,
    }
    if (o.slotName === 'action') {
      obj['resizable'] = false
      obj['filter'] = false
      obj['sortable'] = false
      obj['lockPosition'] = 'right'
      obj['width'] = '100px'
      obj['cellRenderer'] = {
        // template: `<a-tag color="#ff7d00" style="cursor:pointer" @click="a">修改</a-tag>`,
        template: `<a-tag class="tagCss"  v-if="isEdit" @click="a">修改</a-tag>`,
        setup(props: any) {
          const a = () => {
            edit(props.params.data)
          }
          let isEdit = permissionStore.hasPermisson('jtlxlb.xg')
          return {
            a,
            isEdit,
          }
        },
      }
    }
    return obj
  })

  let a = [
    {
      showRowGroup: 'hide_def',
      headerName: '',
      checkboxSelection: true,
      headerCheckboxSelection: true,
      pinned: 'left',
      width: 50,
      resizable: false,
      filter: false,
      sortable: false,
      minWidth: 50,
      maxWidth: 50,
      lockPosition: 'left',
    },
  ]

  tc = a.concat(tc)

  //新增修改弹窗动态绑定的数据
  const formData = reactive<MachineType>({
    typeName: '',
    id: '',
    maxCapacity: 0,
    // typeCode: '',
    remark: '',
    unit: '',
  })

  onMounted(() => {
    pageData.rHeight = document.getElementById('BaseInfoSetting')?.clientHeight
  })

  //此方法返回复选框选中的值
  const { selectedRowKeys, onSelectionChange } = useRowSelection()
  const rowKey = useRowKey('id')

  //此方法用于表格数据动态渲染
  const table = useTable()

  //表格的pagination分页的属性配置
  const pagination = usePagination(doRefresh)

  const total = ref(10)
  const page = ref(1)
  const size = ref(10)
  function PageSize(val: any) {
    pagination.page = val
    doRefresh()
  }

  function change1(val: any) {
    pagination.pageSize = val
    doRefresh()
  }
  function doRefresh() {
    //发起分页查询的请求
    post({
      url: 'planSingle/machineType/getMachineTypePage',
      data: {
        page: pagination.page,
        size: pagination.pageSize,
        typeName: val1,
        typeCode: val2,
      },
    }).then((result: any) => {
      //如果后台返回的状态码为200才能执行后续操作
      if (result.code === 200) {
        //将后台返回的分页查询数据传入，这个方法可获取表格的数据dataList,动态渲染表格，表格的data属性动态绑定table.dataList即可实现动态渲染
        table.handleSuccess(result.data.list)
        //result.data.pages：总页数
        //使用这个方法，可以将pagination总页数pageCount改为-当前用户点击查询后台返回的总页数
        //传入完成之后，即可动态绑定表格渲染
        // pagination.setTotalSize(result.data.total);
        gridOption.value.setRowData(result.data.list)
        total.value = result.data.total
      }
    })
  }

  let val1 = ''
  let val2 = ''
  //查询
  const selectHandler = () => {
    val1 = queryData.typeName
    val2 = queryData.typeCode
    pagination.page = 1
    doRefresh()
  }
  //导出
  const exports = () => {
    // if (selectedRowKeys.value.length === 0) {
    //     Message.error('请先勾选')
    //     return
    // }
    if (gridOption.value.getSelectedRows() === 0) {
      Message.error('请先勾选')
      return
    } else {
      // Modal.confirm({
      // title: '系统提示',
      // content: '是否导出列表数据',
      // onOk() {
      //将表头拼接出来
      let head =
        '<th>类型编号</th><th>类型名称</th><th>极限日产能</th><th>单位</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>'
      //拿到当前表格数据与勾选的行做筛选
      let nowRow = table.dataList.filter(function (o) {
        // return selectedRowKeys.value.indexOf(o["id"]) !== -1;
        return (
          gridOption.value
            .getSelectedRows()
            .map((o: any) => {
              return o.id
            })
            .indexOf(o['id']) !== -1
        )
      })
      let body = ''
      nowRow.forEach(function (o) {
        body += '<tr><td>' + o['typeCode'] + '</td>'
        body += '<td>' + o['typeName'] + '</td>'
        body += '<td>' + o['maxCapacity'] + '</td>'
        body += '<td>' + o['unit'] + '</td>'
        body += '<td>' + o['remark'] + '</td>'
        body += '<td>' + o['createName'] + '</td>'
        body += '<td>' + o['createTime'] + '</td>'
        body += '<td>' + o['updateName'] + '</td>'
        body += '<td>' + o['updateTime'] + '</td>'
        body += '</tr>'
      })
      tableToXlsx(head, '机台类型列表', body)
      // }
      // })
    }
  }

  function tableToXlsx(head: any, filename: any, body: any) {
    const uri = 'data:application/vnd.ms-excel;base64,',
      template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

    const a = document.createElement('a')
    a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
    a.download = filename
    a.click()
    document.removeChild(a)
  }

  // 表格准备事件
  const gridOption = ref()
  const colState = ref()
  const gridReady = (params: any) => {
    gridOption.value = params.api
    colState.value = params.columnApi
  }

  //弹窗的确认和取消
  const formRef = ref<FormInstance>()
  const sideOk = () => {
    formRef.value?.validate().then((err) => {
      if (!err) {
        if (pageData.sideTitle === '修改类型') {
          post({
            url: 'planSingle/machineType/updateMachineType',
            data: [formData],
          }).then((res: any) => {
            if (res.code === 200) {
              formRef.value?.resetFields()
              doRefresh()
              Message.success('修改成功')
              pageData.showAdd = false
            } else {
              Message.error(res.message)
            }
          })
        } else {
          formData.id = null
          post({
            url: 'planSingle/machineType/addMachineType',
            data: [formData],
          }).then((res: any) => {
            if (res.code === 200) {
              formRef.value?.resetFields()
              doRefresh()
              Message.success('新增成功')
              pageData.showAdd = false
            } else {
              Message.error(res.message)
            }
          })
        }
      }
    })
  }

  //新增
  const addHandler = () => {
    // for (let item in formData) {
    //     formData[item] = ''
    // }
    for (var key in formData) {
      if (key === 'id') {
        formData[key] = null
      } else {
        formData[key] = ''
      }
    }
    pageData.showAdd = true
    pageData.sideTitle = '新增类型'
  }

  //删除
  const deleteHandler = () => {
    // if (selectedRowKeys.value.length === 0) {
    //     Message.error('请先勾选')
    //     return
    // }

    if (gridOption.value.getSelectedRows() === 0) {
      Message.error('请先勾选')
      return
    }

    const isArray = selectedRowKeys.value.map((num) => {
      return Number(num)
    })

    Modal.confirm({
      title: '系统提示',
      content: '确认删除选中的数据?',
      onOk() {
        //删除的请求
        post({
          url: '/planSingle/machineType/delMachineType',
          // data: isArray
          data: gridOption.value.getSelectedRows().map((o: any) => {
            return o.id
          }),
        }).then((res: any) => {
          if (res.code === 200) {
            Message.success({
              content: '删除成功',
              duration: 5000,
            })
            pagination.page = 1
            doRefresh()
          } else {
            Message.error(res.message)
          }
        })
      },
    })
  }

  const options = ref<any[]>([])
  const loading = ref(false)

  const handleSearch = (value: any) => {
    if (value) {
      loading.value = true
      window.setTimeout(() => {
        post({
          url: 'planSingle/machineType/getFieldValue',
          data: {
            typeCode: value,
          },
        }).then((res: any) => {
          if (res.code == 200) {
            options.value = res.data
          }
        })
        loading.value = false
      }, 100)
    } else {
      options.value = []
    }
  }

  const options1 = ref<any[]>([])
  const loading1 = ref(false)

  const handleSearch1 = (value: any) => {
    if (value) {
      loading1.value = true
      window.setTimeout(() => {
        post({
          url: 'planSingle/machineType/getFieldValue',
          data: {
            typeName: value,
          },
        }).then((res: any) => {
          if (res.code == 200) {
            options1.value = res.data
          }
        })
        loading1.value = false
      }, 100)
    } else {
      options1.value = []
    }
  }

  const handleSearchs = () => {
    loading.value = true
    window.setTimeout(() => {
      post({
        url: 'planSingle/machineType/getFieldValue',
        data: {
          typeCode: '',
        },
      }).then((res: any) => {
        if (res.code == 200) {
          options.value = res.data
        }
      })
      loading.value = false
    }, 100)
  }
  const handleSearchs1s = () => {
    loading1.value = true
    window.setTimeout(() => {
      post({
        url: 'planSingle/machineType/getFieldValue',
        data: {
          typeName: '',
        },
      }).then((res: any) => {
        if (res.code == 200) {
          options1.value = res.data
        }
      })
      loading1.value = false
    }, 100)
  }
  const handleChange = (_data: any) => {
    table.handleSuccess(_data)
  }
  const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
    flex: 1,
  }
  const huiche = () => {
    doRefresh()
  }

  //:items="['查询', '新增', '删除', '导出',]"
  const permissionStore = usePermission()
  if (permissionStore.hasPermisson('jtlxlb.cx')) {
    pageData.btnList.push('查询')
  }
  if (permissionStore.hasPermisson('jtlxlb.xz')) {
    pageData.btnList.push('新增')
  }
  if (permissionStore.hasPermisson('jtlxlb.sc')) {
    pageData.btnList.push('删除')
  }
  if (permissionStore.hasPermisson('jtlxlb.dc')) {
    pageData.btnList.push('导出')
  }
  const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
    saveOrUpdateGridState01('BasicdataMachineTypes01', gridOption, colState, tc)
  const onColumnMoved = () => {
    saveGridState01()
  }
  const onColumnResized = () => {
    saveGridState01()
  }
</script>

<style scoped lang="less">
  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }
  :deep(.ag-cell.ag-cell-first-right-pinned:not(.ag-cell-range-left):not(.ag-cell-range-single-cell)) {
    text-align: center;
  }
</style>
